<template>
  <div class="product-form-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2>{{ isEdit ? "编辑商品" : "新增商品" }}</h2>
        </div>
        <div class="header-right">
          <el-button @click="handleCancel">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="form-content">
      <el-card shadow="never" class="form-card">
        <el-form
          ref="productFormRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="product-form"
        >
          <!-- 基本信息 -->
          <el-divider content-position="left">基本信息</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="中英文:" prop="language">
                <el-select v-model="formData.language" placeholder="请选择">
                  <el-option label="中文" value="zh" />
                  <el-option label="英文" value="en" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属分类:" prop="categoryId">
                <el-tree-select
                  v-model="formData.categoryId"
                  :data="categoryList"
                  :props="{
                    value: 'id',
                    label: 'categoryName',
                    children: 'children'
                  }"
                  placeholder="请选择分类"
                  filterable
                  check-strictly
                  :render-after-expand="false"
                  clearable
                  :default-expand-all="false"
                  :expand-on-click-node="false"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品名称:" prop="productName">
            <el-input
              v-model="formData.productName"
              placeholder="输入商品名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="品牌:" prop="brand">
                <el-input v-model="formData.brand" placeholder="输入品牌名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型号:" prop="model">
                <el-input v-model="formData.model" placeholder="输入型号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="封面图:" prop="coverImage">
            <Upload
              v-model="formData.coverImage"
              upload-type="image"
              :max-size="2"
              :allowed-types="['image/jpeg', 'image/png', 'image/gif']"
              placeholder="上传封面图"
              tip="只能上传jpg/png/gif文件，且不超过2MB"
              @success="handleCoverUploadSuccess"
              @error="handleCoverUploadError"
            />
          </el-form-item>

          <!-- 价格信息 -->
          <el-divider content-position="left">价格信息</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="售价:" prop="price">
                <el-input-number
                  v-model="formData.price"
                  :min="0.01"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="市场价:" prop="marketPrice">
                <el-input-number
                  v-model="formData.marketPrice"
                  :min="0"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="成本价:" prop="costPrice">
                <el-input-number
                  v-model="formData.costPrice"
                  :min="0"
                  :precision="2"
                  placeholder="0.00"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 商品描述 -->
          <el-divider content-position="left">商品描述</el-divider>
          
          <el-form-item label="商品摘要:" prop="summary">
            <el-input
              v-model="formData.summary"
              type="textarea"
              :rows="3"
              placeholder="输入商品摘要"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="关键词:" prop="keywords">
            <el-input
              v-model="formData.keywords"
              placeholder="输入关键词，多个关键词用逗号分隔"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="规格参数:" prop="specifications">
            <el-input
              v-model="formData.specifications"
              type="textarea"
              :rows="4"
              placeholder="输入规格参数"
            />
          </el-form-item>

          <el-form-item label="商品详情:" prop="detail">
            <div class="rich-editor-container">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 300px; overflow-y: hidden"
                v-model="formData.detail"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </el-form-item>

          <!-- 服务信息 -->
          <el-divider content-position="left">服务信息</el-divider>
          
          <el-form-item label="售后服务:" prop="afterSales">
            <el-input
              v-model="formData.afterSales"
              type="textarea"
              :rows="4"
              placeholder="输入售后服务说明"
            />
          </el-form-item>

          <el-form-item label="包装清单:" prop="packageList">
            <el-input
              v-model="formData.packageList"
              type="textarea"
              :rows="3"
              placeholder="输入包装清单"
            />
          </el-form-item>

          <!-- 状态设置 -->
          <el-divider content-position="left">状态设置</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="商品状态:" prop="productStatus">
                <el-select v-model="formData.productStatus" style="width: 100%">
                  <el-option label="正常" :value="1" />
                  <el-option label="下架" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="推荐商品:" prop="isRecommend">
                <el-switch
                  v-model="formData.isRecommend"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="热门商品:" prop="isHot">
                <el-switch
                  v-model="formData.isHot"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="新品:" prop="isNew">
                <el-switch
                  v-model="formData.isNew"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="精选商品:" prop="isFeatured">
                <el-switch
                  v-model="formData.isFeatured"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支持分销:" prop="isDistribution">
                <el-switch
                  v-model="formData.isDistribution"
                  :active-value="1"
                  :inactive-value="0"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item 
            label="分销比例(%):" 
            prop="distributionRate" 
            v-if="formData.isDistribution"
          >
            <el-input-number
              v-model="formData.distributionRate"
              :min="0"
              :max="100"
              :precision="2"
              style="width: 200px"
            />
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <div class="form-actions">
              <el-button @click="handleCancel">取消</el-button>
              <el-button type="primary" @click="handleSubmit" :loading="loading">
                {{ isEdit ? "更新" : "保存" }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, shallowRef } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import { createProduct, updateProduct, getProductDetail } from "@/api/product/product";
import { getProductCategoryTree } from "@/api/product/category";
import Upload from "@/components/Upload.vue";

// 路由相关
const route = useRoute();
const router = useRouter();
const id = route.params.id as string;
const isEdit = computed(() => !!id);

// 编辑器相关
const editorRef = shallowRef();
const mode = "default";

// 编辑器配置
const toolbarConfig = {
  toolbarKeys: [
    "headerSelect", "blockquote", "|",
    "bold", "underline", "italic", "color", "bgColor", "|",
    "fontSize", "fontFamily", "lineHeight", "|",
    "bulletedList", "numberedList", "todo", "|",
    "justifyLeft", "justifyCenter", "justifyRight", "|",
    "insertLink", "insertImage", "insertTable", "|",
    "undo", "redo", "fullScreen"
  ]
};

const editorConfig = {
  placeholder: "请输入商品详情...",
  MENU_CONF: {
    uploadImage: {
      server: "/api/upload",
      fieldName: "file",
      maxFileSize: 10 * 1024 * 1024,
      allowedFileTypes: ["image/*"]
    }
  }
};

// 表单引用和数据
const productFormRef = ref();
const categoryList = ref([]);
const loading = ref(false);

// 表单数据
const formData = reactive({
  id: "",
  orgId: "",
  categoryId: "",
  language: "zh",
  productName: "",
  brand: "",
  model: "",
  summary: "",
  detail: "",
  afterSales: "",
  packageList: "",
  keywords: "",
  specifications: "",
  price: 0,
  marketPrice: 0,
  costPrice: 0,
  productStatus: 1,
  isRecommend: 0,
  isHot: 0,
  isNew: 0,
  isFeatured: 0,
  isDistribution: 0,
  distributionRate: 0,
  skus: [],
  tagIds: [],
  attachments: [],
  coverImage: ""
});

// 表单验证规则
const formRules = {
  language: [{ required: true, message: "请选择语言", trigger: "change" }],
  productName: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { min: 2, max: 100, message: "商品名称长度在2-100个字符", trigger: "blur" }
  ],
  categoryId: [{ required: true, message: "请选择所属分类", trigger: "change" }],
  price: [
    { required: true, message: "请输入售价", trigger: "blur" },
    { type: "number", min: 0.01, message: "售价必须大于0", trigger: "blur" }
  ]
};

// 编辑器创建回调
const handleCreated = (editor: any) => {
  editorRef.value = editor;
};

// 封面上传回调
const handleCoverUploadSuccess = (response: any) => {
  formData.coverImage = response.url;
  ElMessage.success('封面上传成功');
};

const handleCoverUploadError = () => {
  ElMessage.error('封面上传失败');
};

// 提交表单
const handleSubmit = async () => {
  if (!productFormRef.value) return;
  
  try {
    await productFormRef.value.validate();
    loading.value = true;
    
    const payload = {
      ...formData,
      ...(isEdit.value && { id }),
      distributionRate: formData.isDistribution ? formData.distributionRate : 0,
      attachments: formData.coverImage ? [{ url: formData.coverImage, type: 'cover' }] : []
    };
    
    if (isEdit.value) {
      await updateProduct(id, payload);
      ElMessage.success('商品更新成功');
    } else {
      await createProduct(payload);
      ElMessage.success('商品创建成功');
    }
    
    router.back();
  } catch (error) {
    console.error('Submit error:', error);
    ElMessage.error(isEdit.value ? '商品更新失败' : '商品创建失败');
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消吗？未保存的数据将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.back();
  }).catch(() => {});
};

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await getProductCategoryTree();
    categoryList.value = response.data || [];
  } catch (error) {
    console.error('Fetch categories error:', error);
    ElMessage.error('获取分类列表失败');
  }
};

// 加载商品数据
const loadProductData = async () => {
  if (!isEdit.value) return;
  
  try {
    loading.value = true;
    const response = await getProductDetail(id);
    const product = response.data;
    
    if (product) {
      Object.assign(formData, product);
      // 特殊字段处理
      formData.language = product.language || 'zh';
      formData.skus = product.skus || [];
      formData.tagIds = product.tagIds || [];
      formData.attachments = product.attachments || [];
    }
  } catch (error) {
    console.error('Load product data error:', error);
    ElMessage.error('加载商品数据失败');
  } finally {
    loading.value = false;
  }
};

// 生命周期
onMounted(async () => {
  await fetchCategories();
  await loadProductData();
});

onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy();
  }
});
</script>

<style scoped>
.product-form-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
}

.header-left h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.form-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-card {
  border: none;
  box-shadow: none;
}

.product-form {
  padding: 24px;
}

.product-form .el-divider {
  margin: 32px 0 24px 0;
}

.product-form .el-divider__text {
  font-weight: 500;
  color: #409eff;
}

.product-form .el-form-item {
  margin-bottom: 24px;
}

.product-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

.rich-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.rich-editor-container:hover {
  border-color: #c0c4cc;
}

.rich-editor-container:focus-within {
  border-color: #409eff;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

.form-actions .el-button {
  min-width: 100px;
}


.el-tree-select .el-tree-node__label {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-form-container {
    padding: 12px;
  }
  
  .header-content {
    padding: 12px 16px;
  }
  
  .product-form {
    padding: 16px;
  }
  
  .form-actions {
    flex-direction: column;
    align-items: center;
  }
  
  .form-actions .el-button {
    width: 100%;
    max-width: 200px;
  }
}
</style>
